<?php

namespace app\admin\controller;

use app\admin\model\Expert;
use app\admin\model\ExpertCategory;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use think\Cache;
use think\Controller;
use think\Db;
use app\admin\model\User as U;
use app\admin\model\Member;
use php\Slpic;
use OSS\OssClient;
use OSS\Core\OssException;

class User extends Base
{
    //专家列表
    public function lists($limit = 10, $page = 1)
    {
        if (request()->isAjax()) {
            $list = Db::table('mxkj_expert')
                ->join('mxkj_member', 'mxkj_member.id=mxkj_expert.uid')
//                ->join('mxkj_expert_category','mxkj_expert_category.id=mxkj_expert.category_id')
                ->field('*')
                ->field('mxkj_expert.id as e_id')
                ->field('mxkj_expert.name as e_name')
//                ->field('mxkj_expert_category.name as g_name')
                ->where('mxkj_member.expert_auth', 1)
                ->where('mxkj_expert.status', 1)
                ->where('mxkj_member.state', 1)
                ->where($this->_map)
                ->order('mxkj_expert.id desc')->paginate($limit, false, ['page' => $page]);
            $total = ceil($list->total() / $limit);//获取总页数
            $data = $list->all();
            $list_data = [];
            $url = $this->url;
            foreach ($data as $d) {
                $d['head'] = $url . '/uploads/headimg/' . $d['head'];
                if ($d['is_hot'] == 1) {
                    $d['is_hot'] = '推荐';
                } else {
                    $d['is_hot'] = '未推荐';
                }
                $d['all_gold'] = Db::table('mxkj_wallet_expert_bill')->where('expert_uid', $d['uid'])->sum('count');
                $cate = ExpertCategory::get(['id' => $d['category_id']]);
                $d['g_name'] = $cate['name'];
                $list_data[] = $d;
            }
            $this->ajaxReturn('', $list_data, $list->total());
        } else {
            return $this->fetch('user/user/lists');
        }
    }

    //查看专家认证信息
    public function expert_look()
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $member_id = Cache::get('member_id');
            if (!isset($param['refuse'])) {
                $face_cost = $param['face_cost'];
                $cost = $param['cost'];
                $res1 = Db::table('mxkj_expert')->where('uid', $member_id)->update(['face_cost' => $face_cost, 'cost' => $cost]);
                $res2 = Db::table('mxkj_member')->where('id', $member_id)->update(['expert_auth' => 1]);
                $this->ajaxReturn('已同意', '', '', '200');
            } else {
                $refuse_reason = $param['refuse_reason'];
                Db::table('mxkj_member')->where('id', $member_id)->update(['expert_auth' => '-1', 'refuse_reason' => $refuse_reason]);
                $this->ajaxReturn('已拒绝', '', '', '200');
            }
        } else {
            $certificate_img = $this->url . '/uploads/expert/' . $param['certificate_img'];
            $company_img = $this->url . '/uploads/expert/' . $param['company_img'];
            Cache::set('member_id', $param['uid'], 3600);
            $this->assign('certificate_img', $certificate_img);
            $this->assign('company_img', $company_img);
            return $this->fetch('user/aut_expert/expert_look');
        }
    }

    //是否设置为热门
    public function is_hot()
    {
        $id = $this->_param['id'];
        if (isset($this->_param['cancle'])) {
            $res = DB::name('expert')->where('id', $id)->update(['is_hot' => 0]);
            $this->ajaxReturn('取消成功', '', '', '200');
        } else {
            $res = DB::name('expert')->where('id', $id)->update(['is_hot' => 1]);
            $this->ajaxReturn('置顶成功', '', '', '200');
        }
    }

    //编辑
    public function edit()
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $expert_edit_uid = Cache::get('expert_edit_uid');
            $name = $param['name'];
            $info = $param['info'];
            $cost = $param['cost'];
            $face_cost = $param['face_cost'];
            /*            $bg_id = Db::table('mxkj_expert_category')->where('uid',$expert_edit_uid)->field('id')->find();*/
            $res = Db::table('mxkj_expert')->where('uid', $expert_edit_uid)->update(['category_id' => $param['category_id'], 'name' => $name, 'info' => $info, 'cost' => $cost, 'face_cost' => $face_cost]);
            $this->ajaxReturn('编辑成功', '', '', '200');
        } else {
            $res = Db::table('mxkj_expert')->where('uid', $param['uid'])->find();
            $cate_list = db('expert_category')->where('status', 1)->select();
            Cache::set('expert_edit_uid', $res['uid']);
            $this->assign('g_name', $param['g_name']);
            $this->assign('cate_list', $cate_list);
            $this->assign('res', $res);
            return $this->fetch('user/user/edit');
        }
    }

    //添加专家
    public function add_exp()
    {
        $cate_list = db('expert_category')->where('status', 1)->select();
        $this->assign('cate_list', $cate_list);
        return $this->fetch('user/user/add_exp');

    }

    //添加专家认证
    public function add_exping()
    {
        $user = db('member')->where('mobile', $this->_param['mobile'])->find();
        $this->_param['uid'] = $user['id'];
        $user = db('member')->where('id', $this->_param['uid'])->find();
        if (empty($user)) $this->ajaxReturn("用户不存在", 201);
//        if ($user['identity_auth'] == 0) $this->ajaxReturn('请先实名认证后再操作', 201);

        $exp = db('expert')->where('uid', $this->_param['uid'])->find();
        if ($exp && $user['expert_auth'] == 1) $this->ajaxReturn("该用户已经是专家", 201);


        if ($user['expert_auth'] == 0 && empty($exp)) {
            Db::startTrans();
            try {
                $this->_param['create_time'] = time();
                Db::name('expert')->insert($this->_param);

                db('member')->where('id', $this->_param['uid'])->update(['expert_auth' => 1, 'identity_auth' => 1]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->ajaxReturn("添加失败", 201);
            }

            $this->ajaxReturn("添加成功", 200);
        } else {

            $this->ajaxReturn("该用户已经是专家", 201);

        }
    }

    //用户列表
    public function member_lists($limit = 10, $page = 1)
    {
        if (request()->isAjax()){
            $list = Db::name('user')
                ->field('*')
                ->where($this->_map)
                ->order('')->paginate($limit, false, ['page' => $page]);
            $total = ceil($list->total() / $limit);//获取总页数
            $data = $list->all();
            $list_data = [];
            $url = $this->url;
            foreach ($data as $d) {
//              $d['head'] = $url . '/uploads/headimg/' . $d['head'];
                $list_data[] = $d;
            }
//            dump($list_data);die;
            $this->ajaxReturn('', $list_data, $list->total());
        } else {
            return $this->fetch('user/member/lists');
        }
    }

    public function add_user()
    {
        return $this->fetch('user/member/userform');
    }

    public function add_usering()
    {
        $user = Member::get(['mobile' => $this->_param['mobile']]);
        if($user)$this->ajaxReturn('该手机号已被注册', 201);

        $this->_param['status']=1;
        $this->_param['reg_time']=time();
        $this->_param['password'] = think_ucenter_md5(123456, MANAGER_AUTH_KEY);
        $this->_param['pay_password'] = think_ucenter_md5(123456, MANAGER_AUTH_KEY);
        $this->_param['reg_ip'] = $this->request->ip(1);
        $this->_param['update_time'] = time();

        $temp = Db::name('member')->insert($this->_param);
        if ($temp) {
            $this->success('添加成功!');
        } else {
            $this->success('添加失败!');
        }
    }

    public function edit_user($uid)
    {
        $user = U::get(['id' =>$uid]);
//      dump($user);die;
        $this->assign('user', $user);
        return $this->fetch('user/member/userform');
    }

    public function editing()
    {
        $user1=U::get(['id' => $this->_param['id']]);
//        dump($user1);dump($this->_param);die;
        if($user1['phone']!=$this->_param['phone'])
        {
            $user = U::get(['phone' => $this->_param['phone']]);
            if($user) $this->ajaxReturn('该手机号已被注册', 201);
        }
        unset($this->_param['/admin/user/editing_html']);
        $temp = Db::name('user')->update($this->_param);
        if ($temp) {
            $this->success('编辑成功!');
        } else {
            $this->success('没有修改!');
        }
    }


    //上传头像
    function upload()
    {
        $path = '/uploads/headimg/';
        foreach ($_FILES as $name => $file) {
            $file_types = explode(".", $file['name']);
            $file_type = $file_types [count($file_types) - 1];
            $fn = substr(md5(rand(1, time())), rand(0, 8), 20) . '.' . $file_type;
            $ft = strrpos($fn, '.', 0);
            $fm = substr($fn, 0, $ft);
            $fe = substr($fn, $ft);
            $fp = $_SERVER['DOCUMENT_ROOT'] . $path . $fn;
            $fi = 1;

            if (!in_array(strtolower($file_type), array('gif', 'png', 'jpg', 'jpeg'))) {
                $this->ajaxReturn('格式不对', 201);
            }

            while (file_exists($fp)) {
                $fn = $fm . '[' . $fi . ']' . $fe;
                $fp = $_SERVER['DOCUMENT_ROOT'] . $path . $fn;;
                $fi++;
            }

            $result = move_uploaded_file($file['tmp_name'], $fp);
        }

        if ($result) {

            //上传阿里云OSS
            if(true)
            {
                $root = $_SERVER['DOCUMENT_ROOT'];
                if (is_file($root . '/../extend/oss/autoload.php')) {
                    require_once $root . '/../extend/oss/autoload.php';
                }
                $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
                try {
                    $ossClient->uploadFile($this->bucket, substr($path,1).$fn, $fp);
                    unlink($fp);
                } catch (OssException $e) {
                    printf($e->getMessage() . "\n");
                    return;
                }
            }

            $this->ajaxReturn('修改成功', 200, $fn);
        } else {
            // 上传失败返回错误信息
            $this->ajaxReturn('图片上传失败', 201);
        }
    }

        //用户身份认证列表
        public
        function auth_member_lists($limit = 10, $page = 1)
        {
            if (request()->isAjax()) {

                if (isset($this->_param['identity_auth']) && $this->_param['identity_auth'] == 10) {
                    unset($this->_map['identity_auth']);
                }
                $list = Db::table('mxkj_member')
                    ->field('*')
                    ->where('identity_auth=-1 or identity_auth=2')
                    ->where($this->_map)
                    ->order('mxkj_member.identity_auth desc')->paginate($limit, false, ['page' => $page]);

                $total = ceil($list->total() / $limit);//获取总页数
                $data = $list->all();
                $list_data = [];
                $url = $this->url;
                foreach ($data as $d) {
                    $d['head'] = $url . '/uploads/headimg/' . $d['head'];
                    if ($d['identity_auth'] == 2) {
                        $d['str_identity_auth'] = '认证中';
                    } elseif ($d['identity_auth'] == 1) {
                        $d['str_identity_auth'] = '通过认证';
                    } elseif ($d['identity_auth'] == 0) {
                        $d['str_identity_auth'] = '未认证';
                    } else {
                        $d['str_identity_auth'] = '认证失败';
                    }
                    $list_data[] = $d;
                }
                $this->ajaxReturn('', $list_data, $list->total());
            } else {
                return $this->fetch('user/member/auth_lists');
            }
        }

        //查看身份认证信息
        public
        function identity_look()
        {
            $url = $this->url;
            $param = request()->param();
            if (request()->isAjax()) {
                $member_id = Cache::get('member_id');
                if (!isset($param['refuse'])) {
                    Db::table('mxkj_member')->where('id', $member_id)->update(['identity_auth' => 1]);
                    $this->ajaxReturn('已同意', '', '', '200');
                } else {
                    Db::table('mxkj_member')->where('id', $member_id)->update(['identity_auth' => '-1']);
                    $this->ajaxReturn('已拒绝', '', '', '200');
                }
            } else {

                $img_list_str = "";
                if (!empty($param['card_img']) || $param['card_img'] != '') {
                    $newstr = substr($param['card_img'], 0, strlen($param['card_img']) - 1);
                    if (!empty($newstr) && $newstr != "") {
                        $param['card_img'] = explode(",", $newstr);
                        foreach ($param['card_img'] as $v) {
                            $img_list_str .= $url . '/uploads/card/' . $v . ",";
                        }
                    }
                }
                $img_list_str = substr($img_list_str, 0, strlen($img_list_str) - 1);
                $imgs = explode(",", $img_list_str);

                Cache::set('member_id', $param['id'], 3600);
                $this->assign('real_name', $param['real_name']);
                $this->assign('id_card', $param['id_card']);
                $this->assign('card_img', $imgs);
                return $this->fetch('user/member/identity_look');
            }
        }

        //是否设置封号
        public
        function frozen()
        {
            $id = $this->_param['id'];
            if (isset($this->_param['cancle'])) {
                $res = DB::name('member')->where('id', $id)->update(['state' => 0]);
                $this->ajaxReturn('冻结成功', '', '', '200');
            } else {
                $res = DB::name('member')->where('id', $id)->update(['state' => 1]);
                $this->ajaxReturn('解冻成功', '', '', '200');
            }
        }

        //添加
        public function add_lcc()
        {
            $id = $this->_param['id'];
            $user = DB::name('member')->where('id', $id)->find();
            $user['lcc_wallet'] = $user['lcc_wallet'] + $this->_param['count'];
            DB::name('member')->where('id', $id)->update($user);
            add_bill($id, $this->_param['count'], 2, 2);
            $this->ajaxReturn('添加成功', '', '', '200');

        }

        //专家认证
        public
        function aut_expert_list($limit = 10, $page = 1)
        {
            if (request()->isAjax()) {
                if (isset($this->_param['expert_auth']) && $this->_param['expert_auth'] == 10) {
                    unset($this->_map['expert_auth']);
                    $list = Db::table('mxkj_expert')
                        ->join('mxkj_member', 'mxkj_member.id=mxkj_expert.uid')
//                ->join('mxkj_expert_category','mxkj_expert_category.id=mxkj_expert.category_id')
                        ->field('*')
                        ->field('mxkj_expert.id as e_id')
                        ->field('mxkj_expert.name as e_name')
                        ->where('mxkj_member.expert_auth=-1 or mxkj_member.expert_auth=2')
                        ->where($this->_map)
//                  ->fetchSql(true)
//                   ->where('mxkj_expert.status',1)
//                   ->where('mxkj_member.state',1)
                        ->order('mxkj_member.expert_auth desc')->paginate($limit, false, ['page' => $page]);
                } else {
                    $list = Db::table('mxkj_expert')
                        ->join('mxkj_member', 'mxkj_member.id=mxkj_expert.uid')
//                ->join('mxkj_expert_category','mxkj_expert_category.id=mxkj_expert.category_id')
                        ->field('*')
                        ->field('mxkj_expert.id as e_id')
                        ->field('mxkj_expert.name as e_name')
                        ->where($this->_map)
                        ->where('mxkj_member.expert_auth=-1 or mxkj_member.expert_auth=2')
                        ->order('mxkj_member.expert_auth desc')->paginate($limit, false, ['page' => $page]);

                }
                $total = ceil($list->total() / $limit);//获取总页数
                $data = $list->all();
                $list_data = [];
                $url = $this->url;
                foreach ($data as $d) {
                    $d['head'] = $url . '/uploads/headimg/' . $d['head'];
                    if ($d['expert_auth'] == 2) {
                        $d['expert_auth'] = '待审核';
                    } else {
                        $d['expert_auth'] = '已驳回';
                    }
                    $d['create_time'] = date('Y-m-d H:i:s', $d['create_time']);

                    $cate = ExpertCategory::get(['id' => $d['category_id']]);
                    $v['c_name'] = $cate['name'];

                    $list_data[] = $d;
                }
                $this->ajaxReturn('', $list_data, $list->total());
            } else {
                return $this->fetch('user/aut_expert/lists');
            }
        }

        //认证失败
        public
        function refuse()
        {

            return $this->fetch('user/aut_expert/refuse');

        }

        //用户详情
        public
        function user_info($uid)
        {

            $res = Member::get(['id' => $uid]);
            $res->toArray();
            $expert_auth = $this->expert_auth();
            $res['expert_auth'] = $expert_auth[$res['expert_auth']];
            $identity_auth = $this->identity_auth();
            $res['identity_auth'] = $identity_auth[$res['identity_auth']];
            $this->assign('list', $res);
            return $this->fetch('user/member/info');

        }

    }
